<template>
  <q-dialog
    :model-value="modelValue"
    @update:modelValue="$emit('update:modelValue', $event)"
    persistent
  >
    <q-card style="min-width: 400px">
      <q-card-section>
        <div class="text-h6">重置密码</div>
      </q-card-section>

      <q-card-section>
        <q-form @submit="submitForm" class="q-gutter-md">
          <div class="text-subtitle1">用户: {{ userName }}</div>
          <q-input
            v-model="password"
            label="新密码"
            type="password"
            :rules="[
              (val) => !!val || '密码不能为空',
              (val) => val.length >= 6 || '密码长度不能少于6位',
            ]"
            outlined
          />
          <q-input
            v-model="confirmPassword"
            label="确认密码"
            type="password"
            :rules="[
              (val) => !!val || '请确认密码',
              (val) => val === password || '两次输入的密码不一致',
            ]"
            outlined
          />
          <div class="flex justify-end q-gutter-sm">
            <q-btn label="取消" v-close-popup flat color="primary" />
            <q-btn type="submit" label="确认重置" color="primary" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { resetUserPwd } from '@/api/sys/user'

const props = defineProps({
  modelValue: Boolean,
  userId: Number,
  userName: String,
})

const emit = defineEmits(['update:modelValue', 'submit'])

const password = ref('')
const confirmPassword = ref('')

// 重置表单
function resetForm() {
  password.value = ''
  confirmPassword.value = ''
}

// 监听对话框显示状态
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      resetForm()
    }
  },
)

// 提交表单
async function submitForm() {
  try {
    await resetUserPwd({
      userId: props.userId,
      password: password.value,
    })
    emit('submit')
    emit('update:modelValue', false)
  } catch (error) {
    console.error(' 重置密码失败:', error)
  }
}
</script>
